<?php

namespace App\Http\Controllers\API\Activity;

use Illuminate\Http\Request;
use App\Http\Controllers\API\APIController;

use DB;
use Validator;
use App\Models\API\Activity;
use App\Models\API\ActivityComment;

class CommentController extends APIController
{
    public function index($id)
    {
    	$comments = ActivityComment::where('activity_id', $id)
            ->orderBy('created_at', 'desc')
            ->join('users', 'activity_comments.user_id', '=', 'users.id')
            ->select('activity_comments.*', 'users.user_name', 'users.user_img')
            ->paginate();
        return response()->json($this->setJson(true, $comments), 200);
    }

    public function store(Request $request, $id)
    {
    	$v = Validator::make($request->all(), [
            'user_id'   => 'required',
            'comment'  => 'required'
        ]);

        if ($v->fails())
        {
        	return response()->json($this->setJson(false, $v->errors()), 422);
        }

		if ($v->passes())
		{
			$userInfo = $request->only('user_id', 'comment');
			$res = Activity::find($id)->comment($userInfo);
			return response()->json($this->setJson(true, $res), 200);
		}
    }

    public function destroy(Request $request, $id)
    {
    	$v = Validator::make($request->all(), [
            'user_id'   => 'required'
        ]);

        if ($v->fails())
        {
        	return response()->json($this->setJson(false, $v->errors()), 422);
        }

		if ($v->passes())
		{
			$userId = $request->get('user_id');

            $deleteComment = ActivityComment::where([
                ['id', '=', $id],
                ['user_id', '=', $userId]
            ])->delete();

			return response()->json($this->setJson(true, 'delete_comment_succeed'), 200);
		}
    }

    private function setJson($status, $msg)
    {
        $res = [
            'status' => $status,
            'msg'    => $msg
        ];
        return $res;
    }
}
